<template>
  <div>
    <n-modal

      v-model:show="showModal"
      :mask-closable="false"
      :show-icon="false"
      preset="dialog"
      transform-origin="center"
      :title="formValue.id > 0 ? '编辑erp #' + formValue.id : '手动合并'"
      :style="{
        width: dialogWidth,
      }"
    >
      <n-scrollbar style="max-height: 87vh" class="pr-5">
        <n-spin :show="loading" description="请稍候...">
          <div
            style="
              display: flex;
              justify-content: space-between;
              gap: 20px;
              align-items: flex-start;
            "
          >
            <!-- 左侧列表 -->
            <div style="flex: 1; height: 400px; border: 1px solid #e0e0e0; border-radius: 6px">
              <div
                style="
                  padding: 12px;
                  border-bottom: 1px solid #e0e0e0;
                  background-color: #fafafa;
                  font-weight: 500;
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                "
              >
                <span>门店列表({{ leftList.length }})</span>
                <n-button size="tiny" @click="clearAllPairs">清空所有关联</n-button>
              </div>
              <n-scrollbar style="height: 345px">
                <div style="padding: 8px">
                  <n-list v-if="leftList.length > 0" :bordered="false">
                    <n-list-item
                      v-for="item in leftList"
                      :key="item.id"
                      :class="{
                        'selected-item': isLeftItemSelected(item.id),
                        'paired-item': isLeftItemPaired(item.id),
                      }"
                      @click="selectLeftItem(item)"
                      style="cursor: pointer; border-radius: 4px; margin-bottom: 4px; padding: 10px"
                    >
                      <div
                        style="
                          display: flex;
                          justify-content: space-between;
                          align-items: center;
                          width: 100%;
                        "
                      >
                        <div>
                          <div style="font-weight: 500">
                            {{ item.name || item.title || `项目 ${item.id}` }}
                          </div>
                          <div style="font-size: 12px; color: #909399; margin-top: 4px">
                            ID: {{ item.id }}
                          </div>
                        </div>
                        <div style="display: flex; align-items: center; gap: 8px">
                          <span
                            v-if="isLeftItemPaired(item.id)"
                            style="font-size: 12px; color: #67c23a"
                          >
                            已关联
                          </span>
                          <n-checkbox
                            :checked="isLeftItemSelected(item.id)"
                            @click.stop="selectLeftItem(item)"
                          />
                        </div>
                      </div>
                    </n-list-item>
                  </n-list>
                  <n-empty v-else description="暂无数据" size="small" />
                </div>
              </n-scrollbar>
            </div>

            <!-- 中间关联按钮 -->
            <div
              style="
                display: flex;
                align-items: center;
                flex-direction: column;
                justify-content: center;
                padding-top: 150px;
              "
            >
              <n-button
                type="primary"
                :disabled="!currentLeftSelected || !currentRightSelected"
                @click="createPair"
                style="
                  writing-mode: vertical-rl;
                  text-orientation: mixed;
                  height: 60px;
                  width: 40px;
                "
              >
                关联
              </n-button>
              <div
                v-if="currentLeftSelected && currentRightSelected"
                style="
                  font-size: 12px;
                  color: #909399;
                  margin-top: 8px;
                  text-align: center;
                  writing-mode: horizontal-tb;
                "
              >
                {{ currentLeftSelected.id }} ↔ {{ currentRightSelected.id }}
              </div>
            </div>

            <!-- 右侧列表 -->
            <div style="flex: 1; height: 400px; border: 1px solid #e0e0e0; border-radius: 6px">
              <div
                style="
                  padding: 12px;
                  border-bottom: 1px solid #e0e0e0;
                  background-color: #fafafa;
                  font-weight: 500;
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                "
              >
                <span>ERP列表({{ rightList.length }})</span>
                <span style="font-size: 12px; color: #909399">
                  已关联: {{ pairedItems.length }}
                </span>
              </div>
              <n-scrollbar style="height: 345px">
                <div style="padding: 8px">
                  <n-list v-if="rightList.length > 0" :bordered="false">
                    <n-list-item
                      v-for="item in rightList"
                      :key="item.WH_CD"
                      :class="{
                        'selected-item': isRightItemSelected(item.WH_CD),
                        'paired-item': isRightItemPaired(item.WH_CD),
                      }"
                      @click="selectRightItem(item)"
                      style="cursor: pointer; border-radius: 4px; margin-bottom: 4px; padding: 10px"
                    >
                      <div
                        style="
                          display: flex;
                          justify-content: space-between;
                          align-items: center;
                          width: 100%;
                        "
                      >
                        <div>
                          <div style="font-weight: 500">
                            {{ item.WH_DES }}
                          </div>
                          <div style="font-size: 12px; color: #909399; margin-top: 4px">
                            编码: {{ item.WH_CD }}
                          </div>
                        </div>
                        <div style="display: flex; align-items: center; gap: 8px">
                          <span
                            v-if="isRightItemPaired(item.WH_CD)"
                            style="font-size: 12px; color: #67c23a"
                          >
                            已关联
                          </span>
                          <n-checkbox
                            :checked="isRightItemSelected(item.WH_CD)"
                            @click.stop="selectRightItem(item)"
                          />
                        </div>
                      </div>
                    </n-list-item>
                  </n-list>
                  <n-empty v-else description="暂无数据" size="small" />
                </div>
              </n-scrollbar>
            </div>
          </div>

          <!-- 当前关联关系展示 -->
          <div
            v-if="pairedItems.length > 0"
            style="margin-top: 20px; padding: 16px; background-color: #f5f7fa; border-radius: 6px"
          >
            <h4 style="margin: 0 0 12px 0; font-size: 14px; color: #303133">
              当前关联关系：
              <span style="font-size: 12px; color: #909399; font-weight: normal">
                (共 {{ pairedItems.length }} 对关联)
              </span>
            </h4>

            <div style="max-height: 250px; overflow-y: auto">
              <n-space size="small" vertical>
                <div
                  v-for="(pair, index) in pairedItems"
                  :key="`${pair.leftItem.id}-${pair.rightItem.id}`"
                  style="
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 12px;
                    background: white;
                    border-radius: 6px;
                    border: 1px solid #e0e0e0;
                  "
                >
                  <div style="display: flex; align-items: center; gap: 16px; flex: 1">
                    <!-- 左侧项目 -->
                    <div style="flex: 1; min-width: 0">
                      <div style="font-size: 12px; color: #909399; margin-bottom: 4px"
                        >表A项目:
                      </div>
                      <n-select
                        :value="pair.leftItem.id"
                        :options="getAvailableLeftOptions(pair.leftItem.id)"
                        @update:value="(value) => updatePairLeft(index, value)"
                        placeholder="选择表A项目"
                        style="width: 100%"
                      />
                    </div>

                    <!-- 关联箭头 -->
                    <div style="color: #909399; font-size: 18px; flex-shrink: 0"> ↔</div>

                    <!-- 右侧项目 -->
                    <div style="flex: 1; min-width: 0">
                      <div style="font-size: 12px; color: #909399; margin-bottom: 4px"
                        >表B项目:
                      </div>
                      <n-select
                        :value="pair.rightItem.WH_DES"
                        :options="getAvailableRightOptions(pair.rightItem.WH_CD)"
                        @update:value="(value) => updatePairRight(index, value)"
                        placeholder="选择表B项目"
                        style="width: 100%"
                      />
                    </div>
                  </div>

                  <!-- 删除按钮 -->
                  <n-button
                    size="small"
                    type="error"
                    text
                    @click="removePair(index)"
                    style="margin-left: 12px; color: #f56c6c; flex-shrink: 0"
                  >
                    删除
                  </n-button>
                </div>
              </n-space>
            </div>

            <!-- 合并按钮 -->
            <div style="margin-top: 16px; text-align: center">
              <n-button
                type="primary"
                size="large"
                :disabled="pairedItems.length === 0"
                :loading="merging"
                @click="handleMerge"
              >
                执行合并 ({{ pairedItems.length }} 对关联)
              </n-button>
            </div>
          </div>

          <!-- 当前选择提示 -->
<!--          <div-->
<!--            v-if="currentLeftSelected || currentRightSelected"-->
<!--            style="-->
<!--              margin-top: 20px;-->
<!--              padding: 12px;-->
<!--              background-color: #fff7e6;-->
<!--              border-radius: 6px;-->
<!--              border: 1px solid #ffd591;-->
<!--            "-->
<!--          >-->
<!--            <div style="font-size: 14px; color: #fa8c16; margin-bottom: 8px">-->
<!--              <strong>待关联项目：</strong>-->
<!--            </div>-->
<!--            <div style="display: flex; gap: 20px; align-items: center">-->
<!--              <div v-if="currentLeftSelected" style="flex: 1">-->
<!--                <span style="font-size: 12px; color: #909399">表A选中：</span>-->
<!--                <span style="font-weight: 500">-->
<!--                  {{-->
<!--                    currentLeftSelected.name ||-->
<!--                    currentLeftSelected.title ||-->
<!--                    `项目 ${currentLeftSelected.id}`-->
<!--                  }}-->
<!--                </span>-->
<!--              </div>-->
<!--              <div v-if="currentLeftSelected && currentRightSelected" style="color: #fa8c16">→</div>-->
<!--              <div v-if="currentRightSelected" style="flex: 1">-->
<!--                <span style="font-size: 12px; color: #909399">表B选中：</span>-->
<!--                <span style="font-weight: 500">-->
<!--                  {{-->
<!--                    currentRightSelected.name ||-->
<!--                    currentRightSelected.title ||-->
<!--                    `项目 ${currentRightSelected.id}`-->
<!--                  }}-->
<!--                </span>-->
<!--              </div>-->
<!--            </div>-->
<!--            <div-->
<!--              v-if="currentLeftSelected && currentRightSelected"-->
<!--              style="margin-top: 8px; font-size: 12px; color: #909399"-->
<!--            >-->
<!--              点击中间的"关联"按钮创建关联关系-->
<!--            </div>-->
<!--          </div>-->
        </n-spin>
      </n-scrollbar>
<!--      <template #action>-->
<!--        <n-space>-->
<!--          <n-button @click="closeForm">取消</n-button>-->
<!--        </n-space>-->
<!--      </template>-->
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed } from 'vue';
  import { Edit, View } from '@/api/erp';
  import { State, newState } from './model';
  import { useProjectSettingStore } from '@/store/modules/projectSetting';
  import { useMessage } from 'naive-ui';
  import { adaModalWidth } from '@/utils/hotgo';

  const emit = defineEmits(['reloadTable']);
  const message = useMessage();
  const settingStore = useProjectSettingStore();
  const loading = ref(false);
  const showModal = ref(false);
  const formValue = ref<State>(newState(null));
  const formRef = ref<any>({});
  const formBtnLoading = ref(false);
  const merging = ref(false);

  // 列表数据
  const leftList = ref<any[]>([]);
  const rightList = ref<any[]>([]);

  // 当前选中的单个项目（用于创建关联）
  const currentLeftSelected = ref<any>(null);
  const currentRightSelected = ref<any>(null);

  // 关联对数组
  const pairedItems = ref<Array<{ leftItem: any; rightItem: any }>>([]);

  const dialogWidth = computed(() => {
    return adaModalWidth(1000);
  });

  // 检查左侧项目是否被选中（当前选择）
  function isLeftItemSelected(id: number) {
    return currentLeftSelected.value?.id === id;
  }

  // 检查右侧项目是否被选中（当前选择）
  function isRightItemSelected(id: number) {
    return currentRightSelected.value?.WH_CD === id;
  }

  // 检查左侧项目是否已经在关联对中
  function isLeftItemPaired(id: number) {
    return pairedItems.value.some((pair) => pair.leftItem.id === id);
  }

  // 检查右侧项目是否已经在关联对中
  function isRightItemPaired(id: number) {
    return pairedItems.value.some((pair) => pair.rightItem.WH_CD === id);
  }

  // 选择左侧项目
  function selectLeftItem(item: any) {
    // 如果已经在关联对中，不能再选择
    if (isLeftItemPaired(item.id)) {
      message.warning('该项目已经关联，请先删除现有关联');
      return;
    }
    currentLeftSelected.value = currentLeftSelected.value?.id === item.id ? null : item;
  }

  // 选择右侧项目
  function selectRightItem(item: any) {
    // 如果已经在关联对中，不能再选择
    if (isRightItemPaired(item.WH_CD)) {
      message.warning('该项目已经关联，请先删除现有关联');
      return;
    }
    currentRightSelected.value = currentRightSelected.value?.WH_CD === item.WH_CD ? null : item;
  }

  // 创建关联对
  function createPair() {
    if (!currentLeftSelected.value || !currentRightSelected.value) {
      message.warning('请先选择要关联的项目');
      return;
    }

    // 检查是否已经存在相同的关联
    const existingPair = pairedItems.value.find(
      (pair) =>
        pair.leftItem.id === currentLeftSelected.value.id ||
        pair.rightItem.WH_CD === currentRightSelected.value.WH_CD
    );

    if (existingPair) {
      message.warning('选中的项目已经存在关联关系');
      return;
    }

    // 创建新的关联对
    pairedItems.value.push({
      leftItem: { ...currentLeftSelected.value },
      rightItem: { ...currentRightSelected.value },
    });

    message.success(
      `成功创建关联：${currentLeftSelected.value.name || currentLeftSelected.value.id} ↔ ${currentRightSelected.value.WH_DES || currentRightSelected.value.WH_CD}`
    );

    // 清空当前选择
    currentLeftSelected.value = null;
    currentRightSelected.value = null;
  }

  // 删除关联对
  function removePair(index: number) {
    const pair = pairedItems.value[index];
    pairedItems.value.splice(index, 1);
    message.success(
      `已删除关联：${pair.leftItem.name || pair.leftItem.id} ↔ ${pair.rightItem.WH_DES || pair.rightItem.WH_CD}`
    );
  }

  // 清空所有关联
  function clearAllPairs() {
    if (pairedItems.value.length === 0) {
      message.info('没有关联关系需要清空');
      return;
    }
    pairedItems.value = [];
    currentLeftSelected.value = null;
    currentRightSelected.value = null;
    message.success('已清空所有关联关系');
  }

  // 更新关联对中的左侧项目
  function updatePairLeft(index: number, newLeftId: number) {
    const newLeftItem = leftList.value.find((item) => item.id === newLeftId);
    if (!newLeftItem) return;

    // 检查新项目是否已经在其他关联中
    const existingPair = pairedItems.value.find(
      (pair, i) => i !== index && pair.leftItem.id === newLeftId
    );

    if (existingPair) {
      message.warning('该项目已经在其他关联中使用');
      return;
    }

    pairedItems.value[index].leftItem = { ...newLeftItem };
    message.success('关联关系已更新');
  }

  // 更新关联对中的右侧项目
  function updatePairRight(index: number, newRightId: number) {
    const newRightItem = rightList.value.find((item) => item.WH_CD === newRightId);
    if (!newRightItem) return;

    // 检查新项目是否已经在其他关联中
    const existingPair = pairedItems.value.find(
      (pair, i) => i !== index && pair.rightItem.id === newRightId
    );

    if (existingPair) {
      message.warning('该项目已经在其他关联中使用');
      return;
    }

    pairedItems.value[index].rightItem = { ...newRightItem };
    message.success('关联关系已更新');
  }

  // 获取可用的左侧选项（排除已关联的）
  function getAvailableLeftOptions(currentId?: number) {
    return leftList.value
      .filter(
        (item) =>
          item.id === currentId || !pairedItems.value.some((pair) => pair.leftItem.id === item.id)
      )
      .map((item) => ({
        label: item.name || item.title || `项目 ${item.id}`,
        value: item.id,
      }));
  }

  // 获取可用的右侧选项（排除已关联的）
  function getAvailableRightOptions(currentId?: number) {
    return rightList.value
      .filter(
        (item) =>
          item.WH_CD === currentId || !pairedItems.value.some((pair) => pair.rightItem.WH_CD === item.WH_CD)
      )
      .map((item) => ({
        label: item.WH_DES || item.title || `项目 ${item.id}`,
        value: item.WH_CD,
      }));
  }

  // 处理合并
  async function handleMerge() {
    if (pairedItems.value.length === 0) {
      message.warning('请先创建关联关系');
      return;
    }
    console.log(pairedItems.value,"pairedItems.value")

    try {
      merging.value = true;

      // 准备合并数据
      const mergeData = {
        pairs: pairedItems.value.map((pair) => ({
          leftId: pair.leftItem.id,
          rightId: pair.rightItem.id,
          leftData: pair.leftItem,
          rightData: pair.rightItem,
        })),
      };

      console.log('合并数据:', mergeData);

      // 模拟API调用
      for (let i = 0; i < pairedItems.value.length; i++) {
        Edit({
          id:pairedItems.value[i].erpId ? pairedItems.value[i].erpId : '',
          storeId:pairedItems.value[i].leftItem.id,
          storeName:pairedItems.value[i].leftItem.name,
          WH_DES:pairedItems.value[i].rightItem.WH_DES,
          WH_CD:pairedItems.value[i].rightItem.WH_CD,
        })
      }
      message.success(`成功合并 ${pairedItems.value.length} 对关联关系`);
      closeForm();
      emit('reloadTable');
      // 重置数据
      pairedItems.value = [];
      currentLeftSelected.value = null;
      currentRightSelected.value = null;

      // 可以选择是否重新加载列表
      // await loadLists();
    } catch (error) {
      message.error('合并失败：' + (error.message || '未知错误'));
    } finally {
      merging.value = false;
    }
  }

  // 加载列表数据
  async function loadLists(erpList,storeList) {
    try {
      loading.value = true;

      // 模拟数据
      leftList.value = storeList;

      rightList.value = erpList;
    } catch (error) {
      message.error('加载数据失败：' + (error.message || '未知错误'));
      leftList.value = [];
      rightList.value = [];
    } finally {
      loading.value = false;
    }
  }

  // 提交表单
  function confirmForm(e) {
    e.preventDefault();
    formRef.value.validate((errors) => {
      if (!errors) {
        formBtnLoading.value = true;
        Edit(formValue.value)
          .then((_res) => {
            message.success('操作成功');
            closeForm();
            emit('reloadTable');
          })
          .finally(() => {
            formBtnLoading.value = false;
          });
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  // 关闭表单
  function closeForm() {
    showModal.value = false;
    loading.value = false;
    // 重置所有数据
    currentLeftSelected.value = null;
    currentRightSelected.value = null;
    pairedItems.value = [];
    leftList.value = [];
    rightList.value = [];
  }

  // 打开模态框
  function openModal(state: State,erpList,storeList,list) {
    showModal.value = true;

    // 新增
    if (!state || state.id < 1) {
      formValue.value = newState(state);
      // 加载列表数据
      loadLists(erpList,storeList);
      pairedItems.value = list.map(item => ({
        erpId:item.id,
        leftItem:{
          id:item.storeId,
          name:item.storeName
        },
        rightItem:{
          WH_CD:item.WH_CD,
          WH_DES:item.WH_DES
        }
      }))
      return;
    }

    // 编辑
    loading.value = true;
    View({ id: state.id })
      .then((res) => {
        formValue.value = res;
        // 加载列表数据
        loadLists();
      })
      .finally(() => {
        loading.value = false;
      });
  }

  defineExpose({
    openModal,
  });
</script>

<style lang="less" scoped>
  .selected-item {
    background-color: #e6f7ff !important;
    border: 1px solid #91d5ff !important;
  }

  .paired-item {
    background-color: #f6ffed !important;
    border: 1px solid #b7eb8f !important;
  }

  .selected-item:hover {
    background-color: #bae7ff !important;
  }

  .paired-item:hover {
    background-color: #d9f7be !important;
  }

  .n-list-item {
    transition: all 0.2s ease;
  }

  .n-list-item:hover:not(.selected-item):not(.paired-item) {
    background-color: #f5f5f5;
  }
</style>
